from django.contrib.auth.models import AbstractUser
from django.db import models


class User(AbstractUser):
    """扩展用户模型"""
    nickname = models.CharField(max_length=50, unique=True, verbose_name="昵称")
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True, verbose_name="头像")
    coins = models.IntegerField(default=1000, verbose_name="游戏币")
    wins = models.IntegerField(default=0, verbose_name="胜利次数")
    losses = models.IntegerField(default=0, verbose_name="失败次数")
    level = models.IntegerField(default=1, verbose_name="等级")
    experience = models.IntegerField(default=0, verbose_name="经验值")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    class Meta:
        verbose_name = "用户"
        verbose_name_plural = "用户"
    
    def __str__(self):
        return self.nickname or self.username
    
    @property
    def win_rate(self):
        """胜率"""
        total_games = self.wins + self.losses
        if total_games == 0:
            return 0
        return round((self.wins / total_games) * 100, 2)
    
    @property
    def total_games(self):
        """总游戏数"""
        return self.wins + self.losses
    
    @property
    def matchmaking_rating(self):
        """匹配评分（用于匹配算法）"""
        # 基础评分 = 等级 * 100 + 胜率
        base_rating = self.level * 100 + self.win_rate
        # 根据游戏场次调整（场次越多越稳定）
        games_factor = min(self.total_games * 2, 100)  # 最多加100分
        return base_rating + games_factor
    
    def add_experience(self, exp):
        """增加经验值"""
        self.experience += exp
        # 检查是否升级（每1000经验升一级）
        new_level = (self.experience // 1000) + 1
        if new_level > self.level:
            self.level = new_level
        self.save()
